<?php
/**
 * Created by PhpStorm.
 * User: august
 * Date: 2021/2/23
 * Time: 20:26
 */

namespace app\controller;


use app\validate\MenuValidate;
use Aug\Tools\Tree;
use common\libs\CacheKey;
use common\models\MenuModel;
use think\facade\Cache;
use think\facade\View;

class Menu extends AdminBase
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $list = MenuModel::getList($this->pageData);
            $list = array_column($list, null, 'id');
            foreach ($list as &$row) {
                $row['parent_menu'] = $list[$row['parent_id']]['name'] ?? '顶级菜单';
                unset($row['parent_id']);
            }
            unset($row);

            return $this->returnJson("OK", 0, [
                'list' => $list,
            ]);
        }

        $params = [
            'settings' => [
                'has_checkbox' => true,
                'has_manage' => true,
                'manage' => [
                    'edit' => true,
                    'edit_url' => url('menu/save')->build(),
                    'delete' => true,
                    'delete_url' => url('menu/delete')->build(),
                ],
            ],
            'headers' => [
                'id' => 'ID',
                'name' => '菜单名称',
                'route' => '路由',
                'parent_menu' => '父菜单',
            ]
        ];

        $data = $this->setListData("系统管理—菜单", $params, "列表");
        return view('index', $data);
    }

    public function save()
    {
        $id = intval($_GET['id'] ?? 0);
        if ($id) {
            $model = MenuModel::where('id', $id)->find();
        } else {
            $model = new MenuModel();
        }
        if ($this->request->isPost()) {
            try {
                $postData = array_map('trim', $_POST);
                $this->validate($postData, MenuValidate::class);

                $data = [
                    'name' => $postData['name'],
                    'route' => $postData['route'],
                    'parent_id' => (int)$postData['parent_id'],
                    'data' => empty($postData['data']) ? '' : $postData['data'],
                ];

                if (!$model->save($data)) {
                    return $this->returnJson("保存出错，请联系站长！", 1);
                } else {
                    Cache::delete(CacheKey::KEY_MENU_LIST_HTML);
                    return $this->returnJson("保存成功", 0);
                }
            } catch(\Exception $e) {
                return $this->returnJson("数据不符合要求：" . $e->getMessage(), 1);
            }
        } else {
            $data = $model->toArray();
            if (!$data) {
                $data = [
                    'id' => 0,
                    'name' => '',
                    'route' => '',
                    'parent_id' => 0,
                ];
            }
            if (empty($data['data'])) $data['data'] = '';

            $data['save_url'] = url('menu/save', $data['id'] ? ['id' => $id] : []);
            $allMenus = MenuModel::where('id', '>', 0)->column(['id', 'parent_id', 'name']);
            $data['menus'] = (new Tree($allMenus))->getOptions();
            return view('save', $data);
        }
    }

    public function delete()
    {
        $id = (int) $_POST['id'];
        $model = MenuModel::find(['id' => (int)$id]);
        if (!$model) {
            return $this->returnJson("要删除的记录不存在", 1);
        } else {
            $subIds = MenuModel::getSubIds($id, true);
            /* @var $item \think\Model */
            foreach (MenuModel::whereId('id', $subIds) as $item) {
                $item->delete();
            }
            Cache::delete(CacheKey::KEY_MENU_LIST_HTML);
            return $this->returnJson("删除成功！", 0);
        }
    }
}